#include <iostream>

using namespace std;

// 假设 u08 是 unsigned char 的别名
typedef unsigned char u08;
typedef unsigned int u32;

//// CRC8 函数实现
//u08 CRC8(u08* data, unsigned int len)
//{
//    unsigned char i;
//    unsigned char poly = 0x07;
//    unsigned char init = 0xFF;
//    unsigned char wChar = 0;
//
//    while (len--)
//    {
//        cout<<"len="<<len<<endl;
//        wChar = *(data++);
//        init ^= wChar;
//        for (i = 0; i < 8; i++)
//        {
//            if (init & 0x80)
//            {
//                init = (init << 1) ^ poly;
//            }
//            else
//            {
//                init = init << 1;
//            }
//        }
//    }
//
//    return (init);
//}



int main()
{
    // 示例数据
//    u08 data[] = {0x01, 0x02, 0x03};
    u08 data[] = {0x01};
    unsigned int len = sizeof(data) / sizeof(data[0]);
    cout<<"len="<<len<<endl;

    // 计算 CRC-8
    unsigned char i;
    unsigned char poly = 0x07;
    unsigned char init = 0xFF;
    unsigned char wChar = 0;

    while (len--)
    {
        cout<<"len="<<len<<endl;
        wChar = data[len];
        cout<<"wChar=   0x"<<std::hex <<(int)wChar<<endl;
        init ^= wChar;//按位异或
        cout<<"init=   0x"<<std::hex <<(int)init<<endl;
        for (i = 0; i < 8; i++)
        {
            cout<<"i="<<(int)i<<endl;
            if (init & 0x80)
            {
                cout<<" init = (init << 1) ^ poly;执行前：init&0x80为1=   0x"<<std::hex <<(int)init<<endl;
                init = (init << 1) ^ poly;
                cout<<"init&0x80为1=   0x"<<std::hex <<(int)init<<endl;
            }
            else
            {
                cout<<" init = init << 1;执行前：init&0x80为1=   0x"<<std::hex <<(int)init<<endl;
                init = init << 1;
                cout<<"init&0x80为0=   0x"<<std::hex <<(int)init<<endl;
            }
        }
    }


//    u08 crc = CRC8(data, len);

    // 输出结果
    std::cout << "CRC-8: 0x" << std::hex << (int)init << std::endl;

    return 0;
}


/*
 运行结果：
 D:\CLionProjects\10003\crc8test.exe
len=1
len=0
wChar=   0x1
init=   0xfe
i=0
 init = (init << 1) ^ poly;执行前：init&0x80为1=   0xfe
init&0x80为1=   0xfb
i=1
 init = (init << 1) ^ poly;执行前：init&0x80为1=   0xfb
init&0x80为1=   0xf1
i=2
 init = (init << 1) ^ poly;执行前：init&0x80为1=   0xf1
init&0x80为1=   0xe5
i=3
 init = (init << 1) ^ poly;执行前：init&0x80为1=   0xe5
init&0x80为1=   0xcd
i=4
 init = (init << 1) ^ poly;执行前：init&0x80为1=   0xcd
init&0x80为1=   0x9d
i=5
 init = (init << 1) ^ poly;执行前：init&0x80为1=   0x9d
init&0x80为1=   0x3d
i=6
 init = init << 1;执行前：init&0x80为1=   0x3d
init&0x80为0=   0x7a
i=7
 init = init << 1;执行前：init&0x80为1=   0x7a
init&0x80为0=   0xf4
CRC-8: 0xf4                                                                 (CRC-8余数)
 * */